<template>
	<view>
		<Header :isBack="true">
			<block slot="content">{{title}}</block>
		</Header>

		<!-- 标题栏和状态栏占位符 -->
		<view class="navbar">
			<view class="navbar-user">
				<image class="navbar-headimg" :src="userInfo.headimg" alt=""></image>
				<text class="navbar_text-name">{{userInfo.name}}</text>
			</view>

			<view class="navbar_text">
				<text>{{vip_status}}</text>
			</view>
		</view>
		<view class="place"></view>
		<view class="levels-list">
			<view class="levels-item" @tap="changeVip(index)" v-for="(item,index) in vips"
				:class="{active:index === currentIndex}">
				<text class="levels-item-line1">{{item.name}}</text>
				<text class="levels-item-line2">￥{{item.price}}</text>
				<text class="levels-item-line3">￥{{item.original_price}}</text>
				<view class="levels-item-btn">
					无限次数
				</view>
			</view>
		</view>

		<view class="place"></view>
		<view class="rights-list">
			<image class="rights-list-img" src="@/pages6/static/images/vip.png" mode="aspectFit"></image>
			<view class="rights-details">
				<view class="rights-item">
					<image class="rights-item-img" src="/pages6/static/images/yuyuezhiwei.png" mode="aspectFit"></image>
					<text class="rights-item-text">预约职位</text>
				</view>
				<view class="rights-item">
					<image class="rights-item-img" src="/static/images/lianxidianhua1.png" mode="aspectFit"></image>
					<text class="rights-item-text">联系电话</text>
				</view>
				<view class="rights-item">
					<image class="rights-item-img" src="/static/images/shipinjiaoxue1.png" mode="aspectFit"></image>
					<text class="rights-item-text">视频教学</text>
				</view>
				<view class="rights-item">
					<image class="rights-item-img" src="/pages6/static/images/xinkuaijie1.png" mode="aspectFit"></image>
					<text class="rights-item-text">新快捷</text>
				</view>
			</view>
		</view>

		<view class="place"></view>
		<view class="pay-list">
			<view class="wechat-pay">
				<view class="pay-left">
					<image class="wechat-pay-img1" src="/static/images/weixinzhifu1.png" mode="aspectFit"></image>
					<text class="wechat-pay-text">微信支付</text>
				</view>
				<image class="wechat-pay-img2" v-if="payType == 1" src="@/static/images/xuanzhong.png" mode="aspectFit"
					@tap="selectPayType(1)">
				</image>
				<image class="wechat-pay-img2" v-else src="@/static/images/weixuanzhong.png" mode="aspectFit"
					@tap="selectPayType(1)">
				</image>
			</view>
			<!-- <view class="ali-pay" v-if="!isWechat">
				<view class="pay-left">
					<image class="wechat-pay-img1" src="/static/images/zhifubaozhifu1.png" mode="aspectFit"></image>
					<text class="wechat-pay-text">支付宝支付</text>
				</view>
				<image class="wechat-pay-img2" v-if="payType == 2" src="@/static/images/xuanzhong.png" mode="aspectFit"
					@tap="selectPayType(2)">
				</image>
				<image class="wechat-pay-img2" v-else src="@/static/images/weixuanzhong.png" mode="aspectFit"
					@tap="selectPayType(2)">
				</image>
			</view> -->
		</view>

		<view class="go-pay">
			<view class="go-pay-left">
				<text>实付金额：</text>
				<text class="go-pay-left-price">￥{{currentPrice}}</text>
			</view>

			<text class="go-pay-right" @click="confirm" v-if="isPay">确认支付</text>
			<text class="go-pay-right" style="background-color: #999;" v-else>支付中...</text>
		</view>
	</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				title: '充值中心',
				userInfo: {
					name: '佚名',
					headimg: '/static/images/touxiang.png',
					deadDate: ''
				},

				vips: [],
				currentIndex: 0,
				currentPrice: 0.00,
				payType: 1,
				isWechat: false,
				isPay: true,
				baseUrl: 'https://test.hnliandesy.com/api/',
				appid: "wx5f6ba2c4d12e2e1f",
				openId: '',
				type: 2,
				vip_status: '您当前还不是会员',
			}
		},
		computed: {
			...mapState(['hasLogin']),
		},
		onLoad() {
			//判断是否登录
			// let result = this.$api.isLogin();
			// if (result === false) {
			// 	return false;
			// }

			uni.showLoading({
				title: '加载中...'
			});

			this.loadData();

			// #ifdef H5
			if (this.$wechat && this.$wechat.isWechat()) {
				this.isWechat = true;

				//微信公众号登录
				if (!this.openId) {
					if (window.location.href.indexOf('?code=') !== -1 || window.location.href.indexOf('&code=') !== -1) {
						this.isPay = false;
						let code;
						if (window.location.href.indexOf('?code=') !== -1) {
							code = window.location.href.split('?code=')[1].split('&')[0];
						} else {
							code = window.location.href.split('&code=')[1].split('&')[0];
						}
						//请求后端网络请求
						this.getWxOpenId(code);
					}
				}
			}
			// #endif

			// #ifdef MP-WEIXIN
			this.isWechat = true;
			// #endif
		},
		methods: {
			loadData() {
				this.getBaseInfo()
				this.getVips()
			},

			async getBaseInfo() {
				let token = uni.getStorageSync('token');
				let cate = uni.getStorageSync('cate');

				if (!token) {
					this.$api.msg('token缺失！');
				}
				let url = '/getUserInfo';
				if (cate == 2) {
					url = '/getComInfo';
				}
				let res = await this.$myRequest({
					url: url,
					data: {
						cate: cate,
						token: token
					},
					methods: 'post'
				})

				uni.hideLoading();
				let info = res.data.data;
				if (cate == 1) {
					if (info.realname) {
						this.userInfo.name = info.realname;
					}
					if (info.avatar) {
						this.userInfo.headimg = info.avatar;
					} else {
						this.userInfo.headimg = '/static/images/touxiang.png';
					}

				} else if (cate == 2) {
					if (info.company_name) {
						this.userInfo.name = info.company_name;
					}
					if (info.logo) {
						this.userInfo.headimg = info.logo;
					} else {
						this.userInfo.headimg = '/static/images/company_logo.png';
					}
				}

				if (info.dead_line != '') {
					let time = Math.round(new Date() / 1000);
					if (info.dead_line > time) {
						this.vip_status = '您的会员将在' + info.dead_date + '过期，请及时充值';
					} else {
						this.vip_status = '您的会员已在' + info.dead_date + '过期，请及时充值';
					}
				}
			},

			async getVips() {
				let res = await this.$myRequest({
					url: '/get_vips'
				})
				if (res.data.status == 1) {
					this.vips = res.data.data
					this.currentPrice = this.vips[this.currentIndex].price
				}
			},

			changeVip(index) {
				this.currentIndex = index
				this.currentPrice = this.vips[this.currentIndex].price
			},

			selectPayType(type) {
				this.payType = type;
			},

			async getWxOpenId(code) {
				let res = await this.$myRequest({
					url: '/getWxOpenId',
					data: {
						code: code
					}
				})

				this.openId = res.data.data.openid
				this.confirmPay();
			},

			async confirmPay() {
				uni.showLoading({
					title: '加载中'
				});
				let token = uni.getStorageSync('token');
				if (!token) {
					this.$api.msg('请重新登录', 'none'),
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}, 1000)
				}

				let dataObj = {
					token: token,
					cate: uni.getStorageSync('cate'),
					// tag: tag,
					paytype: 1,
					type: this.type,
					openid: this.openId,
					levelId: this.vips[this.currentIndex].id
				}

				let res = await this.$myRequest({
					url: '/go_pay_vip',
					data: dataObj,
					methods: 'POST',
				})

				if (res.data.status == 2) {
					let info = res.data.data
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							"appId": info.appId, //公众号名称，由商户传入     
							"timeStamp": info.timeStamp, //时间戳，自1970年以来的秒数     
							"nonceStr": info.nonceStr, //随机串     
							"package": info.package,
							"signType": info.signType, //微信签名方式：     
							"paySign": info.paySign //微信签名 
						},
						(res) => {
							if (res.err_msg == "get_brand_wcpay_request:ok") {
								this.payMaskHide = true; // 隐藏当前支付方式选择
								this.isPay = true;
								uni.redirectTo({
									url: '/pages6/pages/my/my'
								})
							} else {
								this.$api.msg('支付失败！')
								this.isPay = true;
							}
						}
					)
				} else if (res.data.status == 1) {

					let paymentData = res.data.data;
					uni.requestPayment({
						timeStamp: paymentData.timeStamp,
						nonceStr: paymentData.nonceStr,
						package: paymentData.package,
						signType: 'MD5',
						paySign: paymentData.paySign,
						success: (res) => {
							this.isPay = true;
							uni.redirectTo({
								url: '/pages6/pages/my/my'
							})
						},
						fail: (res) => {
							this.$api.msg('支付失败！')
							this.isPay = true;
						}
					})
				} else {
					this.$api.msg('非法操作！')
				}

				uni.hideLoading()
			},

			//确认支付
			confirm: async function() {
				this.isPay = false

				let dataObj = {
					token: uni.getStorageSync('token'),
					cate: uni.getStorageSync('cate'),
					paytype: this.payType,
					levelId: this.vips[this.currentIndex].id,
				}

				// #ifdef H5
				if (this.$wechat && this.$wechat.isWechat()) {
					//微信浏览器
					this.getAccessToken();
				} else {
					//非微信浏览器
					dataObj.type = 3;
					switch (this.payType) {
						case 1:
							this.wxPayH5(dataObj);
							break;
						case 2:
							let res = await this.$myRequest({
								url: '/go_pay_vip',
								data: dataObj,
								methods: 'POST',
							})

							let payInfo = res.data

							// console.log(payInfo)

							if (payInfo) {
								document.querySelector('.form').innerHTML = payInfo;
								document.forms[0].submit();
							}
							break;
					}
				}
				// #endif

				// #ifdef APP-PLUS
				dataObj.type = 4;
				switch (this.payType) {
					case 1:
						this.wxPay(dataObj);
						break;
					case 2:
						this.aliPay(dataObj);
						break;
				}

				// #endif

				// #ifdef MP-WEIXIN
				var that = this
				uni.login({
					provider: "weixin",
					success(loginAuth) {
						that.getOpenId(loginAuth.code)
					}
				})

				// #endif
			},

			async getOpenId(code) {
				let res = await this.$myRequest({
					url: '/getAppletOpenId',
					data: {
						code: code
					},
					methods: 'post'
				})

				if (res.data.status == 1) {
					this.openId = res.data.data
					this.type = 1
					this.confirmPay()
				}
			},

			//支付宝支付
			async aliPay(dataObj) {
				uni.getProvider({ //获取可用的支付环境
					service: 'payment',
					success: res => {
						if (~res.provider.indexOf('alipay')) { //先判断用户是否有支付宝支付环境
							uni.showLoading({
								title: '正在调起支付宝支付'
							})

							uni.request({ //再从后端接口获取相关数据配置到orderInfo里，这个接口由后端配置好了，返回结果见下图1-支付宝
								url: this.baseUrl + 'go_pay_vip',
								method: 'POST',
								data: dataObj,
								dataType: "json",
								success: res => {
									// console.log(res)
									if (res.statusCode == 200) {
										if (res.data.status == 0) {
											this.$api.msg(res.data.msg);
											return false;
										}
										let payInfo = res
											.data //拿到后端返回数据后调用下面支付函数（若接口返回obj,需先转成string类型）
										payInfo = payInfo.replace(/\r|\n/ig, "")
										// console.log(payInfo)
										uni.requestPayment({
											provider: 'alipay',
											orderInfo: payInfo, //支付宝订单数据（string类型）
											success: res => {
												uni.hideLoading();
												this.isPay = true;
												uni.redirectTo({
													url: '/pages6/pages/my/my'
												})
											},
											fail: err => {
												uni.hideLoading();
												this.$api.msg('支付失败！');
												this.isPay = true
											}
										});
									}
								},
								fail: () => {
									uni.hideLoading();
									this.$api.msg('服务器开小差了呢，请您稍后再试');
								}
							});
						} else {
							uni.showToast({
								title: '获取支付宝通道失败，请检查您的支付宝是否正常启用',
								icon: 'none'
							})
						}
					}
				});
			},

			//微信支付
			wxPay(dataObj) {
				uni.getProvider({
					service: 'payment',
					success: res => {
						if (~res.provider.indexOf('wxpay')) { //先判断用户是否有微信支付环境（是否安装了微信app）
							uni.showLoading({
								title: '正在调起微信支付'
							})

							uni.request({
								url: this.baseUrl + 'go_pay_vip',
								method: 'POST',
								data: dataObj,
								dataType: "json",
								success: (res) => {
									// console.log(res)
									if (res.data.status == 4) {
										//（这里注意后端返回的数据类型是string还是object，需转成object类型）
										let resobj = res.data.data;
										// console.log(resobj)
										let payInfo = {
											appid: resobj.appid,
											noncestr: resobj.nonce_str,
											package: "Sign=WXPay",
											partnerid: resobj.mch_id,
											prepayid: resobj.prepay_id,
											timestamp: resobj.time_stamp,
											sign: resobj.sign,
										}

										uni.requestPayment({
											provider: 'wxpay',
											orderInfo: payInfo, //微信订单数据（Object类型）
											success: (res) => {
												uni.hideLoading();
												this.isPay = true;
												uni.redirectTo({
													url: '/pages6/pages/my/my'
												})
											},
											fail: (err) => {
												uni.hideLoading();
												this.$api.msg('支付失败！');
												this.isPay = true
											}
										});
									} else if (res.data.status == 0) {
										this.isPay = true
										this.$api.msg(res.data.msg);
									}
								},
								fail: (err) => {
									uni.hideLoading();
									this.isPay = true
									this.$api.msg('服务器开小差了呢，请您稍后再试');
								}
							})
						} else {
							this.isPay = true
							uni.showToast({
								title: '获取微信通道失败，请检查您的微信是否正常启用',
								icon: 'none'
							})
						}
					}
				});
			},

			async wxPayH5(dataObj) {
				let res = await this.$myRequest({
					url: '/go_pay_vip',
					data: dataObj,
					methods: 'POST',
				})

				if (res.data.status == 3) {
					let info = res.data.data
					window.location.href = info;
				}
			},

			async getAccessToken() {
				//重点 这里getWxAppid这个是微信公众号的appid
				if (!this.openId) {
					window.location.href =
						'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
						this.appid +
						'&redirect_uri=' + encodeURIComponent(
							'https://test.hnliandesy.com/h5/#/pages6/pages/my/user-vip') +
						'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
				} else {
					this.confirmPay();
				}
			},
		}
	}
</script>

<style>
	page {
		background-color: #f7f7f7;
	}
</style>

<style lang="scss" scoped>
	.navbar {
		background-image: url('@/pages6/static/images/back4.png');
		width: 750upx;
		height: 510upx;
		background-size: 100%;
		position: relative;
	}

	.navbar-user {
		display: flex;
		position: absolute;
		align-items: center;
		left: 24upx;
		top: 184upx;
	}

	.navbar-headimg {
		width: 110upx;
		height: 110upx;
		border-radius: 110upx;
	}

	.navbar_text-name {
		margin-left: 32upx;
		color: #fff;
		font-size: $font-base;
	}

	.navbar_text {
		position: absolute;
		bottom: 25upx;
		font-size: 28upx;
		left: 56upx;
		color: #9d7557;
	}

	.place {
		height: 28upx;
		width: 100%;
	}

	.levels-list {
		margin-left: 2%;
		width: 96%;
		display: flex;
		justify-content: space-between;
	}

	.levels-item {
		width: 220upx;
		height: 318upx;
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #f9eeeb;
		border-radius: 20upx;
		color: $base-color;
		position: relative;
	}

	.active {
		background-color: $base-color;
		color: #fff;

		.levels-item-btn {
			border: 2upx #fff solid;
		}
	}

	.levels-item-line1 {
		position: absolute;
		top: 45upx;
		font-size: 32upx;
	}

	.levels-item-line2 {
		position: absolute;
		top: 114upx;
		font-size: 40upx;
		font-weight: 600;
	}

	.levels-item-line3 {
		position: absolute;
		top: 185upx;
		font-size: 32upx;
		text-decoration: line-through
	}

	.levels-item-btn {
		position: absolute;
		top: 236upx;
		height: 52upx;
		width: 164upx;
		border: 2upx $base-color solid;
		border-radius: 52upx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28upx;
	}

	.rights-list {
		margin-left: 2%;
		width: 96%;
		height: 287upx;
		background-color: #fff;
		padding: 45upx 62upx 42upx;
		text-align: center;
		border-radius: 20upx;
	}

	.rights-list-img {
		width: 222upx;
		height: 38upx;

	}

	.rights-details {
		width: 100%;
		display: flex;
		justify-content: space-between;
		margin-top: 30upx;
		font-size: 28upx;
	}

	.rights-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.rights-item-img {
		width: 88upx;
		height: 88upx;
	}

	.rights-item-text {
		margin-top: 10upx;
	}

	.pay-list {
		margin-left: 2%;
		width: 96%;
		// height: 225upx;
		background-color: #fff;
		border-radius: 20upx;
	}

	.wechat-pay,
	.ali-pay {
		height: 112upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30upx;
	}

	.pay-left {
		display: flex;
		align-items: center;
	}

	.wechat-pay-text {
		margin-left: 32upx;
		font-size: 28upx;
	}

	.ali-pay {
		border-top: 2upx solid #f7f7f8;
	}

	.wechat-pay-img1 {
		width: 49upx;
		height: 43upx;
	}

	.wechat-pay-img2 {
		width: 36upx;
		height: 36upx;
	}

	.go-pay {
		margin-top: 100upx;
		width: 100%;
		height: 108upx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 42upx;
		font-size: 28upx;
	}

	.go-pay-left-price {
		color: $base-color;
	}

	.go-pay-right {
		background-color: $base-color;
		color: #fff;
		height: 70upx;
		width: 186upx;
		border-radius: 35upx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>